//
//  SearchViewController.m
//  美食百科
//
//  Created by dllo on 16/2/1.
//  Copyright © 2016年 doll. All rights reserved.
//

#import "SearchViewController.h"
#import "NewWorking.h"
#import "ClassModel.h"
#import "StapleTableViewCell.h"
#import "MJRefresh.h"
#import "InforViewController.h"
#import "Reachability.h"
#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height

@interface SearchViewController () <UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)NSMutableArray *array;
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,assign)NSInteger number;
@property(nonatomic,copy)NSString *text;
@property(nonatomic,assign)NSInteger page;
@end

@implementation SearchViewController
- (void)dealloc
{
    [_array release];
    [_tableView release];
    [_text release];

    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.number =1;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10, 17, 20, 30);
    [button setBackgroundImage:[UIImage imageNamed:@"iconfont-jiantou"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        
        //如果无网络,弹窗提示
        if ( 0 == reach.currentReachabilityStatus){
            //弹窗提示
            UILabel *nonconnectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, kWidth, 50)];
            nonconnectionLabel.textAlignment = NSTextAlignmentCenter;
            nonconnectionLabel.backgroundColor = [UIColor redColor];
            nonconnectionLabel.text = @"网络不给力,刷新试试~";
            nonconnectionLabel.textColor = [UIColor whiteColor];
            [self.view addSubview:nonconnectionLabel];
            
            //动画效果,通知栏缓慢出现
            [UIView animateWithDuration:0.6 animations:^{
                nonconnectionLabel.frame = CGRectMake(0, 0, kWidth, 50);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.6 delay:3 options:UIViewAnimationOptionAutoreverse animations:^{
                    nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                    [nonconnectionLabel release];
                    
                } completion:^(BOOL finished) {
                    
                }];
                
                //            [UIView animateWithDuration:1.9 animations:^{
                //                nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                //            //[nonconnectionLabel removeFromSuperview];
                //                [nonconnectionLabel release];
                //            }];
                
            }];
            
        }
    });

    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(button.frame.origin.x+button.frame.size.width+10, 17, kWidth-(button.frame.origin.x+button.frame.size.width+10)-10, 30)];
    searchBar.placeholder = @"请输入要搜索的内容";
    
    
    
    searchBar.delegate = self;
    
    [self.view addSubview:searchBar];
    [searchBar release];
    
    
    

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kWidth, kHeight-64) style:UITableViewStylePlain];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    [self.tableView registerClass:[StapleTableViewCell class] forCellReuseIdentifier:@"search"];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"searchOne"];
    
    
    
    __block SearchViewController *search = self;

    [self.tableView addFooterWithCallback:^{
        [search refreshNumber];
        NSLog(@"🍍");
    }];
    
    self.tableView.footerPullToRefreshText = @"上拉加载数据~";
    
    //上拉到一定程度后加载显示的内容
    self.tableView.footerReleaseToRefreshText = @"松开加载数据~";
    
    //上拉松开后加载显示的内容
    self.tableView.footerRefreshingText = @"数据加载中~";
    
   }



-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.page =1;
    NSLog(@"----%@", searchBar.text);
    self.text = searchBar.text;
    ++self.number;
    [NewWorking GetDayaWithURL:[[NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/search?q=%@&page=1",searchBar.text] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] dic:nil sussess:^(id responseObject) {
        self.array = [NSMutableArray array];
        for (NSDictionary *dic in responseObject[@"foods"]) {
            ClassModel *class= [[ClassModel alloc]init];
            [class setValuesForKeysWithDictionary:dic];
            [self.array addObject:class];
            [class release];
            
        }
        NSLog(@"🍍%ld",self.array.count);
        
        [self.tableView reloadData];
        ++self.page;
    } filed:^(NSError *error) {
        NSLog( @"%@",error);
    }];

    [searchBar resignFirstResponder];
    
    
}


-(void)refreshNumber
{
////            [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/search?q=%@&page=%ld",self.text,self.array.count/20+1];
////        NSLog(@"🍍%ld",self.page);
//        NSLog(@"菠萝");
////    if (self.array.count%30 == 0) {
////        self.page = self.array.count/30+1;
////    }else
//    {
//        //self.tableView.bounces = NO;
////        self.page = (int)self.array.count/30;
//
//        return;
//    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        
        //如果无网络,弹窗提示
        if ( 0 == reach.currentReachabilityStatus){
            //弹窗提示
            UILabel *nonconnectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, kWidth, 50)];
            nonconnectionLabel.textAlignment = NSTextAlignmentCenter;
            nonconnectionLabel.backgroundColor = [UIColor redColor];
            nonconnectionLabel.text = @"网络不给力,刷新试试~";
            nonconnectionLabel.textColor = [UIColor whiteColor];
            [self.view addSubview:nonconnectionLabel];
            
            //动画效果,通知栏缓慢出现
            [UIView animateWithDuration:0.6 animations:^{
                nonconnectionLabel.frame = CGRectMake(0, 0, kWidth, 50);
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.6 delay:3 options:UIViewAnimationOptionAutoreverse animations:^{
                    nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                    [nonconnectionLabel release];
                    
                } completion:^(BOOL finished) {
                    
                }];
                
                //            [UIView animateWithDuration:1.9 animations:^{
                //                nonconnectionLabel.frame = CGRectMake(0, -50, kWidth, 50);
                //            //[nonconnectionLabel removeFromSuperview];
                //                [nonconnectionLabel release];
                //            }];
                
            }];
            
        }
    });

    
    
     NSString *result = [[[NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/search?q=%@&page=%ld",self.text,self.page]
                          stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] stringByReplacingOccurrencesOfString:@" " withString:@"+"];
        [NewWorking GetDayaWithURL:result dic:nil sussess:^(id responseObject) {
        
            if ([responseObject[@"foods"] count]==30) {
                for (NSDictionary *dic in responseObject[@"foods"]) {
                    ClassModel *class= [[ClassModel alloc]init];
                    [class setValuesForKeysWithDictionary:dic];
                    [self.array addObject:class];
                    [class release];
                    
                }
                
                // NSLog(@"🍍%@",self.stapleArray);
                NSLog(@"🍍%ld",self.page);
                [self.tableView reloadData];
                 ++self.page;
                NSLog(@"🍍%ld",self.page);
            }
         [self.tableView footerEndRefreshing];

            
    } filed:^(NSError *error) {
        NSLog(@"%@",error);
         [self.tableView footerEndRefreshing];
        
    }];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //根据结果显示行数
    if (self.array.count == 0&&self.number == 1) {
        return 0;
    }else if (self.array.count == 0&&self.number != 1)
    {
        return 1;
    }
    
    
    else{
        return self.array.count;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果没有搜索结果,显示文字
    if (self.array.count == 0&&self.number != 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchOne"];
        cell.textLabel.textColor = [UIColor lightGrayColor];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.text = @"没有搜索结果~";
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.backgroundColor = [UIColor clearColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }else{
         StapleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
    cell.calory =4;
        cell.string = self.text;
    cell.classModel = self.array[indexPath.row];
        cell.backgroundColor = [UIColor clearColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
  
        
        

   // cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    
    return cell;
    }
    
   
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.array.count == 0) {
        return kHeight/10;
    }else{
        return kHeight/8;
    }
   
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.array.count != 0) {
        InforViewController *infor = [[InforViewController alloc]init];
    infor.number = 4;
    infor.classModel = self.array[indexPath.row];
    [self.navigationController pushViewController:infor animated:YES];
    
    [infor release];
    }
    
}

-(void)backAction:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (BOOL)prefersStatusBarHidden{
    NSLog(@"ne");
    return YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
